import { Layout } from 'antd';
import "./css/App.css";
import PageHeader from './components/PageHeader';
import PageFooter from './components/PageFooter';
import RouterBefore from './router/RouteBefore';
import LoginForm from './components/LoginForm';
import { useState, useEffect } from 'react';
import { whoami, getUserById } from "./api/user"
import { useDispatch } from 'react-redux';
import { changeUserStatus, initUserInfo } from './redux/userSlice';
import { message } from "antd"
const { Header, Footer, Content } = Layout;

function App() {
  const [isModalOpen, setIsModalOpen] = useState(false)
  const dispatch = useDispatch()
  // 恢复登录态
  useEffect(() => {
    const fetchData = async () => {
      try {
        const { data } = await whoami();
        if (data.data) {
          // token有效
          // 根据id获取用户信息
          const res = await getUserById(data.data._id);
          const userInfo = res.data.data;
          // 存储用户信息
          dispatch(initUserInfo(userInfo))
          // 修改登录状态
          dispatch(changeUserStatus(true))
        } else {
          // token过期
          message.warning(data.msg)
          // 移除token
          localStorage.removeItem("token")
        }
      } catch (e) {
        console.log("身份校验失败", e)
      }
    }
    const token = localStorage.getItem("token");
    if (token) {
      fetchData();
    }
  }, [])

  // 关闭弹窗
  const closeModal = () => {
    setIsModalOpen(false)
  }
  // 打开弹窗
  const openModal = () => {
    setIsModalOpen(true)
  }
  return (
    <div className="App">
      <Layout>
        {/* 头部 */}
        <Header>
          <PageHeader handleLogin={openModal}></PageHeader>
        </Header>
        {/* 匹配上的路由页面 */}
        <Content className="content">
          <RouterBefore />
        </Content>
        {/* 底部 */}
        <Footer className='footer'>
          <PageFooter></PageFooter>
        </Footer>
      </Layout>
      {/* 登录弹窗 */}
      <LoginForm isShow={isModalOpen} closeModal={closeModal} />
    </div>
  );
}

export default App;
